package com.example.rotationdemos

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main2.*

class MainActivity2 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        rotate(imageView1,2000)
        rotate(imageView2,1000)
        rotate(imageView3,480)
        rotate(imageView4,100)


//        rootLayout.addView(genImageView2(100))
//        rootLayout.addView(genImageView2(110))
//        rootLayout.addView(genImageView2(480))
//        rootLayout.addView(genImageView2(780))
//        rootLayout.addView(genImageView2(1000))
//        rootLayout.addView(genImageView2(2000))
//        (1..99).forEach {
//            val linearLayout = LinearLayout(this)
//            linearLayout.addView(genImageView(speed))
//            linearLayout.addView(genImageView(speed))
//            linearLayout.addView(genImageView(speed))
//            linearLayout.addView(genImageView(speed))
//            linearLayout.addView(genImageView(speed))
//            rootLayout.addView(linearLayout)
//        }
    }

    private var animationTime = 1000L

    private fun genImageView2(animationTime: Long): ImageView {
        val imageView = ImageView(this)
        imageView.setImageResource(R.drawable.ic_wheel)
        rotate(imageView, animationTime)
        imageView.setOnClickListener {
            val speed = 1000F/animationTime.toFloat()
            Toast.makeText(this, speed.toString(), Toast.LENGTH_LONG).show()
        }
        return imageView
    }

    private fun genImageView(animationTime: Long): ImageView {
        this.animationTime -= 10
        val imageView = ImageView(this)
        imageView.setImageResource(R.drawable.ic_wheel)
        rotate(imageView, animationTime)
        imageView.setOnClickListener {
            Toast.makeText(this, animationTime.toString(), Toast.LENGTH_LONG).show()
        }
        return imageView
    }

    private fun rotate(srcView: View, animateTime: Long) {
        if (animateTime <= 0) {
            return
        }
        srcView.clearAnimation()
        val animation = RotateAnimation(
            0f, 360f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f
        )
        animation.fillAfter = true
        animation.repeatCount = Animation.INFINITE
        animation.duration = animateTime
        animation.interpolator = LinearInterpolator()
        srcView.startAnimation(animation)
    }
}